package com.dayuanit.dy15.atm.handler;

import com.dayuanit.dy15.atm.exception.BizException;
import com.dayuanit.dy15.atm.util.MD5Utils;
import freemarker.template.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import javax.mail.internet.MimeMessage;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class EmailHandler {

    @Autowired
    private MD5Utils md5Utils;

    @Autowired
    private JavaMailSenderImpl javaMailSender;

    @Autowired
    private Configuration freemarkerConfiguration;


    @Value("${email.expire.second}")
    private int expireSecondActive;

    @Value("${atm.host}")
    private String atmHost;

    @Value("${email.active.from}")
    private String from;

    @Value("${email.active.uri}")
    private String emailActiveUri;

    @Value("${email.retrieve.pwd.uri}")
    private String retrievePwdUri;

    public void sendActiveEmail(String email) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.SECOND, expireSecondActive);
        Date date = cal.getTime();

        long expireTime = date.getTime();
        String sign = md5Utils.emailActiveUrl(email, expireTime);

        try {
            StringBuilder sx = new StringBuilder();
            sx.append(atmHost)
                    .append(emailActiveUri)
                    .append("?")
                    .append("email=").append(email)
                    .append("&")
                    .append("expireTime=").append(expireTime)
                    .append("&")
                    .append("sign=").append(sign);

            String activeUrl = sx.toString();
            Map<String, Object> map = new HashMap();
            map.put("activeUrl", activeUrl);
            map.put("host", atmHost);

            sendEmail(from, email, "ATM系统激活邮箱", "bindEmail", map);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("邮件发送失败");
        }
    }

    public void sendForgetPasswordEmail(String email) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.SECOND, expireSecondActive);
        Date date = cal.getTime();

        long expireTime = date.getTime();

        try {
            String sign = md5Utils.emailActiveUrl(email, expireTime);
            StringBuilder sx = new StringBuilder();
            sx.append(atmHost)
                    .append(emailActiveUri)
                    .append("?")
                    .append("email=").append(email)
                    .append("&")
                    .append("expireTime=").append(expireTime)
                    .append("&")
                    .append("sign=").append(sign);

            String forgetPwdUrl = sx.toString();

            Map<String, Object> map = new HashMap<>();
            map.put("rebackPwdUrl", forgetPwdUrl);
            map.put("host", atmHost);

            sendEmail(from, email, "ATM系统找回密码", "forgetPwdEmail", map);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("邮件发送失败");
        }
    }


    /**
     * 发送邮件
     * @param from
     * @param to
     * @param subject
     * @param emailTemplateName
     * @param params
     * @throws Exception
     */
    private void sendEmail(String from, String to, String subject, String emailTemplateName, Map<String, Object> params) throws Exception {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, "GBK");

        mimeMessageHelper.setFrom(from);
        mimeMessageHelper.setTo(to);
        mimeMessageHelper.setSubject(subject);

        //将freemarker邮件模板转为String字符串
        String text = FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfiguration.getTemplate(emailTemplateName + ".ftl"), params);
        mimeMessageHelper.setText(text, true);

        javaMailSender.setDefaultEncoding("GBK");
        javaMailSender.send(mimeMessage);
    }
}
